package com.book.imagedown;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLConnection;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTPConnection {

	private static final String sServer = "192.168.0.18";
	private static final int iPort = 2626;
	private static final String sId = "book";
	private static final String sPassword = "book";

	private static final String sUpDir = "image";
	private static final String sDownDir = "image/";
	private static final String sLogDir = "image/log";
	
	private URLConnection m_client;

	FTPClient ftpClient;

	public FTPConnection() {
		ftpClient = new FTPClient();
	}

	// 서버연결
	public void connect() {

		try {
			ftpClient.connect(sServer, iPort);
			int reply;
			reply = ftpClient.getReplyCode();

			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				System.out.println("서버 연결 거부");
			} else {
				System.out.println("FTP 서버 연결 완료");
			}

		} catch (IOException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {

				}
			}
			System.out.println("FTP 서버 연결 실패");
		}

	}

	public boolean login() {

		try {
			this.connect();
			System.out.println("FTP서버 로그인");
			return ftpClient.login(sId, sPassword);
		} catch (IOException e) {
			System.out.println("FTP서버 로그인 실패");
		}
		return false;

	}

	public boolean logout() {

		try {
			System.out.println("FTP서버 로그아웃");
			return ftpClient.logout();
		} catch (IOException e) {
			System.out.println("FTP서버 로그아웃 실패");
		}
		return false;

	}

	// FTP의 is명령, 모든 파일 리스트 가져옴
	public FTPFile[] list() {

		FTPFile[] files = null;
		try {
			files = this.ftpClient.listFiles();
			System.out.println("파일 리스트 가져오기");
			return files;
		} catch (IOException e) {
			System.out.println("파일 리스트 가져오기 실패");
		}
		return null;

	}

	// 파일을 전송 받음
	public boolean get(String source, String target, String name) {

		boolean flag = false;
		OutputStream output = null;
		try {
			File local = new File(sDownDir, name);
			output = new FileOutputStream(local);
			System.out.println("다운로드할 디렉토리 확인");
		} catch (FileNotFoundException f) {
			System.out.println("다운로드할 디렉토리 없음");
			return flag;
		}

		File file = new File(source);
		try {
			if (ftpClient.retrieveFile(source, output)) {
				flag = true;
			}
			System.out.println("파일 다운로드 완료");
		} catch (IOException e) {
			System.out.println("파일 다운로드 실패");
		}
		return flag;

	}

	/**
	 * The method to download a file and save it onto the local drive of the
	 * client in the specified absolut path
	 * 
	 * @param localfilename
	 *            – the local absolute file name that the file needs to be saved
	 *            as
	 */
	public synchronized boolean downloadFile (String localfilename)
	  {
	    try{
	      InputStream is = m_client.getInputStream();
	      BufferedInputStream bis = new BufferedInputStream(is);

	      OutputStream os = new FileOutputStream(localfilename);
	      BufferedOutputStream bos = new BufferedOutputStream(os);

	      byte[] buffer = new byte[1024];
	      int readCount;

	      while( (readCount = bis.read(buffer)) > 0)
	      {
	        bos.write(buffer, 0, readCount);
	      }
	      bos.close();
	      is.close (); // close the FTP inputstream
	      System.out.println("다운완료ㅛㅛㅛㅛㅛㅛ");

	      return true;
	    }catch(Exception ex){
	    	System.out.println("다운실패");
	      return false;
	    }
	  }

	// 파일 전송 받음
	public File getFile(String source, String name) {

		OutputStream output = null;
		File local = null;
		try {
			// 받는 파일 생성
			local = new File(sDownDir, name);
			output = new FileOutputStream(local);
		} catch (FileNotFoundException e) {
			System.out.println("다운로드할 디렉토리가 없습니다.");
		}

		File file = new File(source);
		try {
			if (ftpClient.retrieveFile(source, output)) {
			}
		} catch (IOException e) {
			System.out.println("파일을 다운로드 못함");
		}
		return local;

	}

	// 파일 전송
	public boolean put(String filename, String targetName) {

		boolean flag = false;
		InputStream input = null;
		File local = null;
		try {
			local = new File(sUpDir, filename);
			input = new FileInputStream(local);
		} catch (FileNotFoundException e) {
			return flag;
		}

		try {
			if (ftpClient.storeFile(targetName, input)) {
				flag = true;
			}
		} catch (IOException e) {
			System.out.println("파일을 전송하지 못했습니다.");
		}
		return flag;

	}

	// 서버 디렉토리 이동
	public void cd(String path) {

		try {
			ftpClient.changeWorkingDirectory(path);
		} catch (IOException e) {
			System.out.println("폴더 이동 못함");
		}

	}

	public void disconnect() {

		try {
			ftpClient.disconnect();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void setFileType(int iFileType) {

		try {
			ftpClient.setFileType(iFileType);
		} catch (Exception e) {
			System.out.println("파일 타입을 설정하지 못했습니다.");
		}

	}

}
